var imagePath;

var replayTime = 5;
var mediaTimer;
var clipTimer;

var isPlaying = false;
var isRecording = false;
var isDragging = false;
var startRecTimes = new Array();
var endRecTimes = new Array();
var curClip = 0;
var curClipPrinted = 0;
var p_currentPosition = 0;
var p_totalTime = 0;
var scaleLength = 284;

var hdnClips;
var p;

function InitPlayer()
{
	p = document.getElementById("Player");
	hdnClips = document.getElementById("hdnClips");
}

function Play()
{	
	if(!isPlaying)
	{
		p.uiMode = "none";
		p.controls.play();		
		mediaTimer = window.setInterval("syncMediaStats()",1000);	
		document.getElementById("btnPlay").src = imagePath + "btnPause.jpg";
		isPlaying = true;
	}
	else
		pause();
}

function pause()
{
	p.controls.pause();
	document.getElementById("btnPlay").src = imagePath + "btnPlay.jpg";
	clearTimers();
	isPlaying = false;
}

function Stop()
{	
	if( Number(p.versionInfo.substring(0, p.versionInfo.indexOf("."))) >= 9 ) 
	{
		p.uiMode = "invisible";
	}
	
	pause();	
	endRecord();	
	
	//reset indicators
	document.getElementById("ScaleBar").style.backgroundPosition = -scaleLength;
	document.getElementById("mediaTime").innerHTML = "00:00 / " + secondsToMediaTime(p_totalTime);		
	
	//stop movie
	p.controls.stop();
}

function Mute()
{
	p.settings.mute = !p.settings.mute;
	if(p.settings.mute)
		document.getElementById("btnMute").src = imagePath + "btnMute_off.jpg";
	else
		document.getElementById("btnMute").src = imagePath + "btnMute.jpg";
}

function Replay()
{	
	if(p_currentPosition < replayTime)
		p.controls.currentPosition = 0		
	else
		p.controls.currentPosition = (p_currentPosition - replayTime);
}

function Record()
{
	if(!isRecording)
		startRecord();
	else
		endRecord();
}

function startRecord()
{	
	if(isPlaying)
	{	
		if(endRecTimes.length != startRecTimes.length)
			endRecord();
				
		document.getElementById("mediaRec").innerHTML = "<img src=\"" + imagePath + "rec_anim.gif\" />";
		startRecTimes[curClip] = Math.floor(p_currentPosition);
		isRecording = true;	
		addCaret();
	}	
}

function endRecord()
{
	if(endRecTimes.length != startRecTimes.length)
	{
		document.getElementById("mediaRec").innerHTML = "";
		if(p_currentPosition > 0)
			endRecTimes[curClip] = Math.floor(p_currentPosition);
		else
			endRecTimes[curClip] = Math.floor(p_totalTime);
		curClip++;
		isRecording = false;
		addCaret();		
	}
	previewClips();
}

function addCaret()
{
	var elCaret = document.createElement("img");
	if(isRecording)
		elCaret.className = "mediaStartCaret";
	else
		elCaret.className = "mediaEndCaret";
	
	var scale = document.getElementById("ScaleBar");
	
	mx = findPosX(scale);	
	my = findPosY(scale);
	
	if(isRecording)
		elCaret.style.left = ((Math.round(scaleLength * p_currentPosition)) / p_totalTime) + mx;
	else if(p_currentPosition > 0)
		elCaret.style.left = ((Math.round(scaleLength * p_currentPosition)) / p_totalTime) + mx + 8;
	else
		elCaret.style.left = ((Math.round(scaleLength * p_totalTime)) / p_totalTime) + mx;
		
	elCaret.style.top = my - 2;
	
	document.getElementById("playerContainer").appendChild(elCaret);		
}

function toggleCarets(show)
{
	var mc = document.getElementById("playerContainer");
	
	var carets = getElementsByClass(mc, "mediaStartCaret", "img"); 	
	for(i = 0; i < carets.length; i++)
	{
		if(show)
			carets[i].style.display = "block";
		else
			carets[i].style.display = "none";
	}
		
	carets = getElementsByClass(mc, "mediaEndCaret", "img");
	for(i = 0; i < carets.length; i++)
	{
		if(show)
			carets[i].style.display = "block";
		else
			carets[i].style.display = "none";
	}
}

function previewClips()
{		
	var s = "";
	while(curClipPrinted < startRecTimes.length)
	{
		
		s += (curClipPrinted + 1) + ". <input type=\"text\" maxLength=\"100\" id=\"clipTitle" + curClipPrinted + "\" /><br/>";		
		s += "&nbsp;&nbsp;&nbsp; " + secondsToMediaTime(startRecTimes[curClipPrinted]) + " - " + secondsToMediaTime(endRecTimes[curClipPrinted]) + "<br/><br/>";
		curClipPrinted++;
	}
	if(s != "")
		document.getElementById("savedClipsInput").innerHTML += s;
		
	if(curClipPrinted > 0)
	{
		document.getElementById("savedClips").style.display = "block";
	}	
}

function SaveClips()
{
	if(hdnClips != null)
	{	
		var title = "";
	
		for(i=0; i < startRecTimes.length; i++)
		{
			title = document.getElementById("clipTitle" + i).value;
			if(title != "")
				hdnClips.value += startRecTimes[i] + "^" + endRecTimes[i] + "^" + title + "^";
			else
			{
				hdnClips.value = "";
				alert("Please provide a title for clip number " + (i + 1) + ".  Or click Cancel to return to the video.");
				return;
			}
		}
		control = undefined;
		sendAsyncData("User/StudioAsync.aspx?savedClips=" + hdnClips.value + "&postID=" + g_curPostID + "&url=" + p.Url);		
	}
	else
	{
		alert("no local data store found.");
	}
}

function CancelSave()
{
	document.getElementById("savedClips").style.display = "none";
}

function StartDrag()
{	
	isDragging = true;
	pause();
}

function AnimDrag()
{	
	if(isDragging)
	{
		var scale = document.getElementById("ScaleBar");
		mx = event.x + get_scroll_dimensions()[0];
		scalex = mx - findPosX(scale)
		scale.style.backgroundPosition = scalex - scaleLength;
				
		document.getElementById("mediaTime").innerHTML = secondsToMediaTime(Math.floor((p_totalTime * scalex) / scaleLength)) + " / " + secondsToMediaTime(p_totalTime);		
	}		
}

function CheckDrag()
{	
	if(isDragging)
	{
		StopDrag();
	}
}

function StopDrag()
{	
	isDragging = false;
	mx = event.x + get_scroll_dimensions()[0];	
	
	dragEndPoint = mx - findPosX(document.getElementById("ScaleBar"));		
	p.controls.currentPosition = (p_totalTime * dragEndPoint) / scaleLength;
	Play();
}

function LoadMovie(newUrl, imgUrl, newPostID)
{
	
	Stop();
	resetPlayer();
	p.Url = newUrl;
	g_curPostID = newPostID;
	previewImage = document.getElementById("playerPreviewImage");
	if(typeof(previewImage) == "object") 
	{
		previewImage.src = imgUrl;
	}
	/*
	var movieTitle = document.getElementById("movieTitle");
	if(typeof(movieTitle) == "object")
	{
		movieTitle.innerHTML = title + " <a href=\"../ShowPost.aspx?postid=" + newPostID + "\">#</a>";
	}
	loadNinerClips(newPostID); //async*/
}

function resetPlayer()
{
	g_curPostID = 0;
	
	isPlaying = false;
	isRecording = false;
	isDragging = false;	

	p_currentPosition = 0;
	p_totalTime = 0;
	
	clearClips();
}

function clearClips()
{
	//did we do any recording?
	if(startRecTimes.length > 0)
	{
		startRecTimes = new Array();
		endRecTimes = new Array();	
		curClip = 0;
		curClipPrinted = 0;
		document.getElementById("savedClipsInput").innerHTML = "";	
		document.getElementById("savedClips").style.display = "none";	
		hdnClips.value = "";
		
		var mc = document.getElementById("playerContainer");
		
		var carets = getElementsByClass(mc, "mediaStartCaret", "img"); 	
		for(i = 0; i < carets.length; i++)
			mc.removeChild(carets[i]);
			
		carets = getElementsByClass(mc, "mediaEndCaret", "img");
		for(i = 0; i < carets.length; i++)
			mc.removeChild(carets[i]);
	}	
}

function syncMediaStats()
{
	p_totalTime = Math.round(p.currentMedia.duration);
	p_currentPosition = Math.round(p.controls.currentPosition);
	
	document.getElementById("ScaleBar").style.backgroundPosition = (((p_currentPosition * 100) / p_totalTime) * 3) - scaleLength;	
	document.getElementById("mediaTime").innerHTML = secondsToMediaTime(p_currentPosition) + " / " + secondsToMediaTime(p_totalTime);
	
	if(p_totalTime == Math.ceil(p.controls.currentPosition))
		Stop();
}

function secondsToMediaTime(seconds)
{
	var mediaTime = "";
	
	hours = Math.floor(seconds / 3600);
	if(hours > 0)
	{
		mediaTime += hours + ":";
		seconds = seconds - (hours * 3600);
	}	
		
	minutes = Math.floor(seconds / 60);
	if(minutes > 0)
	{
		if(minutes >= 10)
			mediaTime += minutes + ":";
		else
			mediaTime += "0" + minutes + ":";
		seconds = seconds - (minutes * 60);
	}
	else
	{
		mediaTime += "00:";
	}
	
	if(seconds >= 10)
		mediaTime += seconds;
	else
		mediaTime += "0" + seconds;
	
	return mediaTime;
}

function clearTimers()
{
	clearInterval(clipTimer);
	clearInterval(mediaTimer);
}

function AutoOver(el){
	if(el.id == "btnPlay" && isPlaying)
		el.src = imagePath + "btnPause_on.jpg";
	else if(el.id == "btnMute" && p.settings.mute)
		el.src = imagePath + "btnMute_off_on.jpg";
	else
		el.src = imagePath + el.id + "_on.jpg";
}

function AutoOut(el){
	if(el.id == "btnPlay" && isPlaying)
		el.src = imagePath + "btnPause.jpg";
	else if(el.id == "btnMute" && p.settings.mute)
		el.src = imagePath + "btnMute_off.jpg";
	else
		el.src = imagePath + el.id + ".jpg";
}

/*------------- General Async Methods -------------*/

var control, oXMLHTTP, tempControl;

function makeAsyncCall(pageUrl)
{
	var url = "http://" + g_Domain + "/channel9/";
	
	if( !g_DEBUG )
		url = "http://" + g_Domain + "/";
	
	url += pageUrl;
	
	if (window.XMLHttpRequest) 
		oXMLHTTP = new XMLHttpRequest();
    else //IE
		oXMLHTTP = new ActiveXObject("Msxml2.XmlHttp.3.0");

	oXMLHTTP.onreadystatechange = onReadyStateChange;
	oXMLHTTP.open( "GET", url, true );
	oXMLHTTP.send("");
}

function onReadyStateChange()
{	
	if( oXMLHTTP.readyState == 4 )
	{			
		if( typeof(control) == "object" )
		{
			control.innerHTML = oXMLHTTP.responseText;
		}		
	}
}

function sendAsyncData(pageUrl)
{
	var url;
	
	if( !g_DEBUG )
		url = "http://channel9.msdn.com/";
	else
		url = "http://" + g_Domain + "/channel9/";
	
	url += pageUrl;
	
	if (window.XMLHttpRequest) 
		oXMLHTTP = new XMLHttpRequest();
    else //IE
		oXMLHTTP = new ActiveXObject("Msxml2.XmlHttp.3.0");

	oXMLHTTP.onreadystatechange = onDataReturned;
	oXMLHTTP.open( "GET", url, true );
	oXMLHTTP.send("");
}

function onDataReturned()
{	
	if( oXMLHTTP.readyState == 4 )
	{	
		if( Number(oXMLHTTP.responseText) > 0 )
		{
			clearClips();
		}		
	}
}
/*------------- Media Finder -------------*/
function FindMoviesByTagID(tagID, source)
{
	tempControl = document.getElementById("more" + tagID);
	if(tempControl.innerHTML == "")
	{
		var mf = document.getElementById("mediaFinder");
		
		//clear
		var els = getElementsByClass(mf, "taggedVideos", "div"); 	
		for(i = 0; i < els.length; i++)
			els[i].innerHTML = "";
			
		//waiting...
		control = tempControl;	
		control.innerHTML = "<img src=\"" + imagePath + "9guyfade.gif\" />";
		
		makeAsyncCall("User/StudioAsync.aspx?tagid=" + tagID);
	}	
}

/*------------- Niner Clips -------------*/

function loadNinerClips(postID)
{
	control = document.getElementById("myClips");
	if(typeof(control) == "object")
	{
		control.innerHTML = "<img src=\"" + imagePath + "9guyfade.gif\" />";
		makeAsyncCall("User/StudioAsync.aspx?postid=" + postID);
	}	
}


